import base64
# import rsa
import binascii

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5

from Crypto.Util.Padding import pad
# message = 'Hello, World!'
#
#
# 正确的公钥格式
key = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArnXiDSVRYHJ+xCeDQlpAn1Pm4xB2W8F/KgZ30PsVbN4zPyJbGt1Hj3OuTx/v7To6RoDmk4dao4v7qh50QD7KxP0Ck/YQG7fQlFagpFVWQN+2H2Mcgyo6H9EciNAWJdVa2r3toPge6sJluhwoMOXnGe+1uhchEsoINAfi5v3XwwwHnB1NXHzZNo6AKg90a6tY4U4zXAq8s3kp3UQmyB/WrTU6GBRskL2sB5LzOh5Bcsn9mnqp1Chgh1Ws4/uhd4xVYeF+TEC4BGo2UTeWRKQe4X/+l2C7WXuWEng8IHyvpZc+4sVejTvSNn3zMxmlgHvgby5Cjk3pBTnG7XjrOwJpJwIDAQAB'
pub_key_str = '-----BEGIN PUBLIC KEY-----\n' + key + '\n-----END PUBLIC KEY-----'
# # 加载公钥
# public_key = rsa.PublicKey.load(pub_key_str.encode())

# pub_key_str = '''-----BEGIN PUBLIC KEY-----
# MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqyR7UfW9mLPspFa9Fayh
# WeJfTjZFuCTROIrcgFPc5CuN8qeaG+3/gX9eIChUC8hcpSvVxcUrHfYRa4CQ7gLx
# EbtcmCwvSeXyDzfSnCzApWlUfUpG2a9HsLXMpVyPodNUwwQFYfofO949CbDhqEXy
# Pl8t0NARcID/hAhHkAQ13hx2ezpynpqNqz5NXmDALZvAmeEL36rlsT2UrLyjYNd6
# rCre0OWq+NIyLEEtgSrSSKj2HALUnGxyB2cruGRjDMFIVo2DdQP6oqeiS5flASFz
# dSrfoIblGLn8kFKzMVdz9tBj+Dfx9nTowNo991Oc62oluzcU/AN8X1+YHdfuH+dC
# UQIDAQAB
# -----END PUBLIC KEY-----
# '''

# 加载公钥
public_key = RSA.import_key(pub_key_str)



# 创建 PKCS1_v1_5 加密器
cipher = PKCS1_v1_5.new(public_key, randfunc=lambda x: '1'.encode())

# # 加密字符串
# encrypted_message = cipher.encrypt(message.encode())


def pkcs7_pad(data, block_size):
    return pad(data, block_size)


def encrypt(message):

    # 加密字符串
    # original_message = "hello"
    # encrypted_message = rsa.encrypt(t.encode(), public_key)
    # PKCS#7 填充
    block_size = 256  # RSA-2048 的最大填充块大小
    padded_message = message.encode()
    # pkcs7_pad(message.encode(), block_size - 11)  # RSA 加密时需要额外的 11 字节

    # RSA 加密时需要额外的 11 字节
    encrypted_message = cipher.encrypt(padded_message)
    # 将加密后的字节数据转换为十六进制字符串，便于显示
    encrypted_message_hex = binascii.hexlify(encrypted_message).decode()
    return encrypted_message_hex


def encrypt_long(t):
    n = ""
    r = (public_key.n.bit_length() + 7 >> 3) - 11  # 计算最大块大小
    i = split_string_by_length(t, r)  # 分割字符串

    # 对每个分割后的部分进行加密并拼接结果
    for part in i:
        n += encrypt(part)
    # print(n)
    return hex2b64(n)


def split_string_by_length(t, e, n=None):
    if n is None:
        n = []

    r = list(t)
    i = 0
    for o in range(len(r)):
        a = ord(r[o])
        if a <= 127:
            i += 1
        elif a <= 2047:
            i += 2
        elif a <= 65535:
            i += 3
        else:
            i += 4

        if i > e:
            s = t[:o]
            n.append(s)
            return split_string_by_length(t[o:], e, n)

    n.append(t)
    return n


def hex2b64(hex_string):
    """
    将十六进制字符串转换为Base64字符串。

    :param hex_string: 十六进制字符串
    :return: Base64字符串
    """
    i = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    r = ""
    e = 0
    while e + 3 <= len(hex_string):
        n = int(hex_string[e:e + 3], 16)
        r += i[n >> 6] + i[63 & n]
        e += 3
    if e + 1 == len(hex_string):
        n = int(hex_string[e:e + 1], 16)
        r += i[n << 2]
    elif e + 2 == len(hex_string):
        n = int(hex_string[e:e + 2], 16)
        r += i[n >> 2] + i[(3 & n) << 4]
    while (len(r) & 3) > 0:
        r += "="
    return r

# 示例用法
if __name__ == '__main__':
    # print(encrpt_v4('{}'))
    # print(hex2b64('aa823fa7b768f0163bde50d11b418a11bdbea029458f8b99cabc3f7e60c41139817adf12513e8c9f96f0a4a0466ba721ac3a78dda40c96f0dcca6eb5b0e9f884489f6916832e7e43755ffe206745c670c6f541a97a695071a068b7f8fdbb88af8b095b6c31a39ce9ae27343e7f8e2452f58dd21b7925a9fbe7e983be0ba675e95bc4f879484a471211fdabe077c676012865134f1f26d2787b097057881c5188c836eb2ac0fec66ee373012878f50e74e9561813eeb3b7bf4cbe5e8e1fa0ef7093c6a28ca127946c0c2a04b165e0b58b4ccd40bfa7125a5383fb3068aed9f009f993e3118739b234362e61707c1776d3472db12d9f71cc9353f62d9ed7a75bef600038630e61d6af1373a080060602f2fa2537dec5d47f8e15cc4ebbd0d771d9d09a4eb8ff05db225a6d32ee5c06662ec828d7d96581eda22420bef8a84b199bea4f47698d91e392b682c476e1d05240ee897cdbe25be77c232e8782167f65333071834d3d15008f02f268006a47d8a59edfd988b91aa318857dac574b8e8f02830d5dbbc546d21266bb524a86854f8dc0ed4a9d7a328923c7a8abb63bb5b93decb797c7da419f6f071066ab377081cd35a701039bd3b8bb17d9733434885f450009cc8b22c36aaf729ca21776fa5c86c83bcc38be0d58b687be46e7fb444b5559f85f42dd3781b546662271b2fcc29020095d6fd41c12e2d5ece2070f1c6a2e46be0381aa1da0580df57a0adb45cff583aa6f9ed8427b390dadd3544497b6827dbe82e155a6c5c075dc8d2b5dc29a5169da7c671f701653302f1c737ae5d54a0428d2f98fd0621bf2616def8c0b16c2e2d5489782aab3044b2ea475f0b2cc30e761377ac90b84b00f25255443c848332bda36f690005438549ca417496b812010fef216aa89b0925e2180a64d69fd274349d0cfa3b78a48ef1322e15eb621d36df26f9b4ac1a32331c8be4a64150c5a96591b3d1690782960baeb547b3a6671fbfb42e627008a11532b42be5aaa397f8d411f08c187456875a44bacd33b3fd08794fd3a0dd37d5bd0bc05622795a57cd1322e393d605bda3c45a25f141b917a'))
    print(encrpt(
        '{"ecologyMemberId":"","balance":"","memberTag":"","productCategory":502,"paymentMode":1,"contact":{"name":"尤伟","phone":"15136107396","faceImageId":"","credentialType":"1","credential":"410305196507294514","visitorPoint":""},"createCells":[{"productPriceId":"1781","startDate":"2025-01-26","visitors":[{"credential":"410305196507294514","credentialType":"1","name":"尤伟","index":0,"idIndex":"01737903808971","idCardType":"idcard","countryAlphaCode":"","countryName":"","faceImageId":""}],"bookQuantity":1,"salePrice":91,"settleMoney":91,"timeCode":""}],"scheduleCode":"","performScreeningId":"","priceGroupType":3,"giftCouponQrCodeId":66883,"partnerMerchantId":2289,"token":"123.52.213.15@4b7c0cb71247bb6d83778165174de538"}'
    ))
